package photo.view;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.squareup.picasso.Picasso;
import java.io.File;
import org.an.proj.contacts.R;

public class UploadImageView extends FrameLayout {

  @Bind(R.id.iv_upload) ImageView ivUpload;
  @Bind(R.id.btn_delete) ImageView btnDelete;
  @Bind(R.id.fl_progress) FrameLayout flProgress;
  @Bind(R.id.tv_re_upload) TextView tvReupload;

  private int state;
  public static final int STATE_ADD = 0;
  public static final int STATE_PREPER_UPLOAD = 1;
  public static final int STATE_UPLOADING = 2;
  public static final int STATE_SHOW = 3;
  public static final int STATE_UPLOAD_FAILED = 4;

  private Activity activity;
  private UploadImageListener mUploadImageListener;

  //在progress变化达到此百分比时才进行progress变更操作，以减少view刷新次数
  private static final int MIN_PROGRESS_CHANGE_PERCENT = 2;

  public UploadImageView(Context context) {
    super(context);
    init(context);
  }

  public UploadImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
  }

  public UploadImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
  }

  void init(Context context) {
    if (context instanceof Activity) {
      this.activity = (Activity) context;
    } else {
      throw new IllegalArgumentException("the init context must be an activity");
    }

    View view = LayoutInflater.from(activity).inflate(R.layout.view_upload_image, this, true);
    ButterKnife.bind(this, view);
    btnDelete.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        if (mUploadImageListener != null) {
          mUploadImageListener.delImage(UploadImageView.this, null);
        }
      }
    });
    ivUpload.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        if (mUploadImageListener != null) {
          mUploadImageListener.onImageClick(UploadImageView.this, state);
        }
      }
    });

    setState(STATE_ADD);
  }

  public int getState() {
    return state;
  }

  /**
   * 根据不同状态处理View显示
   */
  public void setState(int state) {
    this.state = state;
    switch (state) {
      case STATE_ADD:
        ivUpload.setImageResource(R.drawable.icon_add_photo);
        //LianjiaImageLoader.loadCenterCrop(activity, R.drawable.icon_add_photo,
        //    R.drawable.img_defult, R.drawable.img_defult, ivUpload);
        //ivUpload.setBackgroundResource(0);
        btnDelete.setVisibility(GONE);
        flProgress.setVisibility(GONE);

        break;
      case STATE_PREPER_UPLOAD:
        //ivUpload.setBackgroundResource(R.drawable.shape_upload_image);
        btnDelete.setVisibility(VISIBLE);

        flProgress.setVisibility(VISIBLE);
        if (ivUpload.getHeight() != 0) {
          flProgress.getLayoutParams().height = ivUpload.getHeight();
          flProgress.requestLayout();
        } else {
          ivUpload.post(new Runnable() {
            @Override public void run() {
              flProgress.getLayoutParams().height = ivUpload.getHeight();
              flProgress.requestLayout();
            }
          });
        }
        tvReupload.setText("");
        break;
      case STATE_UPLOADING:
        //tvReupload.setText(
        //    UIUtil.getString(MyApplication.getInstance(), R.string.ht_cancel_upload));
        btnDelete.setVisibility(GONE);
        break;
      case STATE_SHOW:
        //ivUpload.setBackgroundResource(R.drawable.shape_upload_image);
        btnDelete.setVisibility(VISIBLE);
        flProgress.setVisibility(GONE);
        break;
      case STATE_UPLOAD_FAILED:
        //ivUpload.setBackgroundResource(R.drawable.shape_upload_image);
        btnDelete.setVisibility(VISIBLE);

        flProgress.setVisibility(VISIBLE);
        if (ivUpload.getHeight() != 0) {
          flProgress.getLayoutParams().height = ivUpload.getHeight();
          flProgress.requestLayout();
        } else {
          ivUpload.post(new Runnable() {
            @Override public void run() {
              flProgress.getLayoutParams().height = ivUpload.getHeight();
              flProgress.requestLayout();
            }
          });
        }
        tvReupload.setText("点击重新上传");
        break;
      default:
    }
  }

  /**
   * 处理进度显示
   *
   * @param currentBytes 已完成bytes
   * @param contentLength 全部bytes
   */
  public void setUploadProgress(long currentBytes, long contentLength, boolean done) {
    ViewGroup.LayoutParams params = flProgress.getLayoutParams();
    if (done) {
      // 完成状态交给接口success时处理 progress时不再负责

      //flProgress.setVisibility(GONE);
      //params.height = 0 ;
      //flProgress.requestLayout();
    } else {
      flProgress.setVisibility(VISIBLE);
      int viewHeight = getHeight();
      if (viewHeight != 0) {
        int newHeight = (int) (viewHeight * (1 - ((float) currentBytes / contentLength)));
        if (params.height - newHeight > (float) viewHeight * MIN_PROGRESS_CHANGE_PERCENT / 100f) {
          //减少view刷新次数
          params.height = newHeight;
          flProgress.requestLayout();
        }
      }
    }
  }

  public void showImage(final File file) {
    if (file == null) {
      ivUpload.setImageResource(R.drawable.img_defult);
    } else {
      Picasso.with(activity)
          .load(file)
          .placeholder(R.drawable.img_defult)
          .error(R.drawable.img_defult)
          .centerCrop()
          .fit()
          .into(ivUpload);
    }
  }

  public void showImage(final String url) {
    if (getHeight() != 0) {
      String imageUrl = url + "." + getHeight() + "x.jpg";
      //LianjiaImageLoader.loadCenterCrop(activity, imageUrl, R.drawable.img_defult,
      //    R.drawable.img_defult, ivUpload);
    } else {
      post(new Runnable() {
        @Override public void run() {
          String imageUrl = url + "." + getHeight() + "x.jpg";
          //LianjiaImageLoader.loadCenterCrop(activity, imageUrl, R.drawable.img_defult,
          //    R.drawable.img_defult, ivUpload);
        }
      });
    }
  }

  public interface UploadImageListener {

    void delImage(UploadImageView uploadImageView, String message);

    void onImageClick(UploadImageView uploadImageView, int state);
  }

  public void setUploadImageListener(UploadImageListener uploadImageListener) {
    this.mUploadImageListener = uploadImageListener;
  }
}
